package com.huage.courseplatform.application.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.huage.courseplatform.application.mapper.*;
import com.huage.courseplatform.application.model.entity.*;
import com.huage.courseplatform.application.model.vo.BusinessTeacherFlowRecordVO;
import com.huage.courseplatform.application.service.BusinessService;
import com.huage.courseplatform.framework.core.impl.BaseServiceImpl;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;


import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

import static com.huage.courseplatform.framework.constant.StatusConstants.ACCOUNT_NORMAL;

@Service
public class BusinessServiceImpl extends BaseServiceImpl<BusinessMapper, Business> implements BusinessService {

    @Resource
    ConfigMapper configMapper;

    @Resource
    BusinessMapper businessMapper;

    @Resource
    TeacherMapper teacherMapper;

    @Resource
    StudentMapper studentMapper;

    @Resource
    PeriodMapper periodMapper;

    @Resource
    BusinessTeacherFlowRecordMapper businessTeacherFlowRecordMapper;

    @Override
    @Cacheable(cacheNames="Service:BusinessService:userId",key = "#userId",unless="#result == null")
    public List<Business> getBusinessListByUserId(String userId) {
        return businessMapper.getBusinessListByUserId(userId);
    }

    @Override
    public List<Business> getPeriodBusinessListByUserId(String userId) {
        List<Student> students = studentMapper.getByUserId(userId);
        if (CollectionUtils.isEmpty(students)){
            return null;
        }
        List<String> studentIds = students.stream().map(Student::getId).collect(Collectors.toList());
        HashSet<String> businessIdSet = new HashSet<>();
        studentIds.forEach(studentId->{
            List<String> businessIds = periodMapper.getBusinessIdsByStudentId(studentId);
            if(!CollectionUtils.isEmpty(businessIds)){
                businessIdSet.addAll(businessIds);
            }
        });
        List<Business> businessList = new ArrayList();
        if(!CollectionUtils.isEmpty(businessIdSet)){
            businessIdSet.forEach(businessId->{
                Business business = businessMapper.selectById(businessId);
                businessList.add(business);
            });
        }
        return businessList;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @Caching(evict={@CacheEvict(cacheNames = "Service:BusinessTeacherFlow:id", key = "#businessTeacherFlowRecord.id"),
            @CacheEvict(cacheNames = "Service:BusinessTeacherFlow:teacherId", key = "#businessTeacherFlowRecord.teacherId"),
            @CacheEvict(cacheNames = "Service:BusinessTeacherFlow:businessId", key = "#businessTeacherFlowRecord.businessId")})
    public void teacherAudit(BusinessTeacherFlowRecord businessTeacherFlowRecord) {
        BusinessTeacherFlowRecord flowRecord = businessTeacherFlowRecordMapper.selectById(businessTeacherFlowRecord.getId());
        Assert.notNull(flowRecord,"找不到审核流程");

        /*
            只可以通过当前用户的单据
         */
        String userId = (String)StpUtil.getLoginId();
        List<Business> userBusinessList = businessMapper.getBusinessListByUserId(userId);
        //判断商户id是否存在于集合
        Boolean isOwnBusiness = userBusinessList.stream()
                .filter(business-> business.getStatus() == ACCOUNT_NORMAL)
                .map(Business::getId).collect(Collectors.toList()).contains(flowRecord.getBusinessId());
        Assert.isTrue(isOwnBusiness,"用户权限不够");


        businessTeacherFlowRecordMapper.updateById(businessTeacherFlowRecord);
        teacherMapper.insertBusinessTeacherById(flowRecord.getBusinessId(),flowRecord.getTeacherId());
    }

    @Override
    @Cacheable(cacheNames="Service:BusinessTeacherFlow:businessId",key = "#id",unless="#result == null")
    public List<BusinessTeacherFlowRecordVO> getTeacherApplyList(String id) {
        return businessMapper.getTeacherApplyList(id);
    }


    @Override
    public List<Business> getBusinessByLocation(Double longitude, Double latitude) {
        //获取配置表距离
        String business_distance = configMapper
                .selectOne(new QueryWrapper<SysConfig>().lambda().eq(SysConfig::getCode,"BUSINESS_DISTANCE"))
                .getValue();
        return businessMapper.getBusinessByLocation(longitude,latitude,Integer.parseInt(business_distance));
    }
}
